import logging

from flask import render_template, current_app, session, request, jsonify, g

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/newslist')
def get_news_list():
    '''
    获取指定分类的新闻列表
    1. 获取参数
    2. 校验参数
    3. 查询数据
    4. 返回数据
    :return:
    '''
    # 1. 获取参数
    category_id = request.args.get('cid',1)  # 分类id
    page = request.args.get('page',1)  # 页数
    per_page = request.args.get('per_page',constants.HOME_PAGE_MAX_NEWS)  # 每页多少条数据，不传就默认
    # 2. 校验参数
    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
        print('页数%d' % page)
        print('每页数据%d' % per_page)
        print('分类id为%d' % category_id)
    except Exception as e:
        logging.error(e)
        return jsonify(error=RET.PARAMERR,errmsg='参数有误')
    # 3. 查询数据并分页
    filters = []
    # 如果分类id不为1，那么添加分类id的过滤，如果等于1就是获取当前(最新)新闻就好
    if category_id != 1:
        filters.append(News.category_id == category_id)
    try:
        # 把filters解包传入,paginate如果没有前面两个参数，会使用默认的不会报错
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        # 获取查询出来的数据
        news_list = pagination.items
        # 获取到总页数
        total_page = pagination.pages
        # 当前页对象
        current_page = pagination.page
        print(news_list)
        print(total_page)
        print(current_page)
    except Exception as e:
        return jsonify(error=RET.DBERR, errmsg='数据查询失败')

    news_li = []
    for news in news_list:
        news_li.append(news.to_basic_dict())
    # 4返回数据
    return jsonify(error=RET.OK, errmsg='成功',cid=category_id,currentPage=current_page,totalPage=total_page,newsList=news_li)




@index_blu.route('/')
@user_login_data
def index():
    '''
    登录状态判断
    :return:
    '''
    user = g.user
    # 111点击排行
    # 获取点击排行数据
    news_list = None
    try:
        # 查询数据按点击量降序，只查询前10条
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        logging.error(e)

    click_news_list = []
    # 遍历新闻列表，把里面的新闻对象转换为字典
    for news in news_list:
        click_news_list.append(news.to_basic_dict())
    # 222新闻分类
    # 获取新闻分类数据
    categorys = Category.query.all()
    # 定义列表保存分类数据
    categorys_list = []
    for category in categorys:
        categorys_list.append(category.to_dict())
    data = {
        'user_info': user.to_dict() if user else None,
        'click_news_list': click_news_list,
        'categorys_list': categorys_list
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
